//
//  AccountDataProvider.m
//  PigMarket
//
//  Created by Felix on 2019/3/27.
//  Copyright © 2019 felix.pigmarket.oc. All rights reserved.
//

#import "AccountDataProvider.h"

// 沙盒路径
#define AccountsPath [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"accountsPath"]

@interface AccountDataProvider ()

/**
 accounts
 */
@property (nonatomic , strong) NSMutableArray *accounts;

@end

@implementation AccountDataProvider

+ (AccountDataProvider *)sharedInstance {
    static AccountDataProvider *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[AccountDataProvider alloc] init];
    });
    return instance;
}

- (void)saveAccount:(NSString *)account {
    [self getAccounts];
    if (!self.accounts) {
        self.accounts = [NSMutableArray array];
    }
    if ([self.accounts containsObject:account]) {
        [self.accounts removeObject:account];
    }
    if (self.accounts.count == 5) {
        [self.accounts removeLastObject];
    }
    [self.accounts insertObject:account atIndex:0];
    [NSKeyedArchiver archiveRootObject:self.accounts toFile:AccountsPath];
}

- (void)deleteAccount:(NSString *)account {
    [self getAccounts];
    if ([self.accounts containsObject:account]) {
        [self.accounts removeObject:account];
        [NSKeyedArchiver archiveRootObject:self.accounts toFile:AccountsPath];
    }
}

- (NSMutableArray<NSString *> *)getAccounts {
    if (!self.accounts) {
        self.accounts = [NSMutableArray array];
    }
    self.accounts = [NSKeyedUnarchiver unarchiveObjectWithFile:AccountsPath];
    return self.accounts;
}

@end
